//
//  MYGCommunityListView.swift
//  MYGrow
//
//  Created by lance on 2024/3/2.
//

import UIKit
import MJRefresh

enum MYGCommunityListActionType {
    case selected
    case like
    case collect
    case comment
}

class MYGCommunityListView: UIView {
    // MARK: - Property
    var communityListAction: ((MYGCommunityListActionType, Int) -> ())?
    var loadDataAction: ((Bool) -> ())?
    private var cellModels: [MYGCommunityCellModel] = []
    // MARK: - init
    override init(frame: CGRect) {
        super.init(frame: frame)
        configUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - UI
    private func configUI() {
        self.addSubview(communityTableView)
        communityTableView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    }
        
    // MARK: - Public funcs
    public func reload(with cellModels: [MYGCommunityCellModel]) {
        self.cellModels = cellModels
        communityTableView.mj_footer?.isHidden = cellModels.count == 0
        communityTableView.reloadData()
    }
    
    public func reload() {
        communityTableView.reloadData()
    }
    
    public func endRefreshing(noMoreData: Bool) {
        communityTableView.endRefreshing(noMoreData: noMoreData)
    }
    
    public func beginRefreshing() {
        communityTableView.beginRefreshing()
    }
    
    // MARK: - lazy load
    private lazy var communityTableView = {
        let tableView = MYGPageTableView(frame: .zero, style: .plain)
        tableView.separatorStyle = .none
        tableView.backgroundColor = .white
        tableView.delegate = self
        tableView.dataSource = self
        tableView.rowHeight = UITableView.automaticDimension
        tableView.estimatedRowHeight = 188
        tableView.register(cellWithClass: MYGCommunityQuestionCell.self)
        tableView.loadDataAction = {[weak self] isRefreshing in
            self?.loadDataAction?(isRefreshing)
        }
        return tableView
    }()

}


extension MYGCommunityListView: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        cellModels.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let model = cellModels[indexPath.row]
        let cell = tableView.dequeueReusableCell(withClass: MYGCommunityQuestionCell.self)
        cell.likeAction = {[weak self] in
            self?.communityListAction?(MYGCommunityListActionType.like, indexPath.row)
        }
        cell.model = model
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        communityListAction?(.selected ,indexPath.row)
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        self.endEditing(true)
        self.superview?.endEditing(true)
    }
}
